"""

.. module:: a2p_servicetest
.. moduleauthor:: @author: 

The purpose of this module is ... 
   
.. seealso:: modules :mod:`<module>`

*Constants*:
"""

# Imports
#
import logging
import time
import unittest

from datastore.database import DataStore
from datastore.resource import Resource
from datastore.spaces import Spaces
from datastore.uri import Uri
from runtime.rt import Runtime
from runtime.nodelogger import NodeLogger
from a2p_service import A2PServiceAPI, A2PService

# Constants
#

# Classes
#

class A2PServiceTest(unittest.TestCase):
    """This class is a unit test for A2PServiceAPI and A2PService. 

    **Constants**:
    """

    @staticmethod
    def init():

        A2PServiceTest.ds = DataStore(filename="U:\\yarra-node-test\\eplanning.datastore")
        A2PServiceTest.spaces = Spaces()
        
        # Initialise Runtime and Spaces. This results in the loading of spaces' 
        # namespace bindings.
        #
        rt = Runtime(A2PServiceTest.ds)
        rt.spaces = A2PServiceTest.spaces
        rt.start_service_manager_and_config_service()
        
        A2PServiceTest.logger = NodeLogger.getLogger('eplanning.spear.a2pservicetest.A2PServiceTest')
        A2PServiceTest.SpearReferenceNumber = ""
    
    def setUp(self):
        """This function initialises the unit test.
        """
        
        self.logger = A2PServiceTest.logger
        
        self.spaces = A2PServiceTest.spaces
        self.SpearReferenceNumber = A2PServiceTest.SpearReferenceNumber

        A2PServiceTest.is_calledback = False
        
    def tearDown(self):
        """This function finalises the unit test.
        
        :param param_1: <class> or <type>
        :param param_2: <class> or <type>
        :rtype: <return type>
        """
        
        self.logger.log(logging.DEBUG, "===================== tearDown()")
    
    def test_get_0(self):
        """This function tests a request for an Accept/Reject Rejection. 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting Accept/Reject Rejection")
        
        A2PServiceTest.SpearReferenceNumber = "S008090V"
        
        rs = A2PServiceAPI(A2PServiceTest.spaces).send_acceptreject_application(A2PServiceTest.SpearReferenceNumber, acceptreject_flag=A2PServiceAPI.ACCEPTREJECT_REJECT, reject_reason="This is a rejection reason from A2PServiceTest.")
        
        if (rs.metadata_has_key(Uri('term:base/datastore/resource/type')) is True) and \
           (rs.get_metadata(Uri('term:base/datastore/resource/type')) == Uri('term:eplanning/spear/a2p_service/a2presponse')):
            self.logger.log(logging.DEBUG, "===================== Spear request response (%s)" % (rs.pretty_print()))
        
        if (rs.has_var("error") is True) and \
           (len(rs.get_var("error")) > 0):
            self.logger.log(logging.DEBUG, "===================== Spear request response error (%s)" % rs.get_var("error"))
        
        if (rs.has_var(Uri('a2p:request/uri')) is True) and \
           (rs.get_var(Uri('a2p:request/uri')) == Uri('a2puserreq:acceptrejectapplication')):
            self.logger.log(logging.DEBUG, "===================== Spear send-acceptrejectapplication response")
        
        if (rs.has_var('a2p:request/uuid') is True):
            self.logger.log(logging.DEBUG, "===================== Spear send-acceptrejectapplication response UUID (%s)" % (rs.get_var('a2p:request/uuid')))
    
    def test_get_1(self):
        """
        This function tests a request for the Spear application list. 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting Spear application list")
        
        rs = A2PServiceAPI(A2PServiceTest.spaces).get_application_list(is_current=True)
        
        # Response from A2P should look like:
        #
        #  <metadata>
        #    <item type="term:type/uri" key="term:base/datastore/resource/type">
        #      term:eplanning/spear/a2p_service/a2presponse
        #    </item>
        #  </metadata>
        #  <content>
        #    <item type="term:type/string" key="a2p:request/uri">
        #      a2puserreq:getapplicationlist
        #    </item>
        #    <item type="term:type/string" key="a2p:request/uuid">
        #      7b6eaa12-4fd3-4d7d-8844-3aa8303a39fa
        #    </item>
        #    <dict key="apps_dict_dict">
        #      <dict key="S007533P">
        #        <item type="term:type/string" key="Action">
        #        </item>
        #        <item type="term:type/string" key="Advertised_Indicator">
        #          Application Advertised
        #        </item>
        #        <item type="term:type/string" key="Air_Indicator">
        #        </item>
        #        <item type="term:type/string" key="App_id">
        #          7605
        #        </item>
        #        <item type="term:type/string" key="Appealed_Indicator">
        #        </item>
        #        <item type="term:type/string" key="Applicant_Contact">
        #          HAF eDA Applicant A
        #        </item>
        #        <item type="term:type/string" key="CC_Version">
        #          100
        #        </item>
        #        <item type="term:type/string" key="Council_Hosted_Indicator">
        #        </item>
        #        <item type="term:type/string" key="Council_Ref">
        #          PortPhillipRef001
        #        </item>
        #        <item type="term:type/string" key="Date_Lodged_With_Responsible_Authority">
        #          28/05/2010
        #        </item>
        #        <item type="term:type/string" key="Objected_Indicator">
        #          Online Objection submitted
        #        </item>
        #        <item type="term:type/string" key="Plan_Number">
        #          -
        #        </item>
        #        <item type="term:type/string" key="Property_Details">
        #          12 BRIDGE STREET, PORT MELBOURNE VIC 3207
        #        </item>
        #        <item type="term:type/string" key="Status">
        #          Referred
        #        </item>
        #        <item type="term:type/string" key="Type">
        #          Planning Permit (Dwelling: Construct: 1)
        #        </item>
        #        <item type="term:type/string" key="spear_ref">
        #          S007533P
        #        </item>
        #        <item type="term:type/string" key="state">
        #          summaryinfoonly
        #        </item>
        #      </dict>
        #    </dict>
        #  </content>
        
        if (rs.metadata_has_key(Uri('term:base/datastore/resource/type')) is True) and \
           (rs.get_metadata(Uri('term:base/datastore/resource/type')) == Uri('term:eplanning/spear/a2p_service/a2presponse')):
            self.logger.log(logging.DEBUG, "===================== Spear request response (%s)" % (rs.pretty_print()))
        
        if (rs.has_var("error") is True) and \
           (len(rs.get_var("error")) > 0):
            self.logger.log(logging.DEBUG, "===================== Spear request response error (%s)" % rs.get_var("error"))
        
#        if (rs.has_var(Uri('a2p:request/uri')) is True) and \
#           (rs.get_var(Uri('a2p:request/uri')) == Uri('a2puserreq:getapplicationlist')):
#            self.logger.log(logging.DEBUG, "===================== Spear get-application-list response")
        
        if (rs.has_var('a2p:request/uuid') is True):
            self.logger.log(logging.DEBUG, "===================== Spear get-application-list response UUID (%s)" % (rs.get_var('a2p:request/uuid')))
        
        self.logger.log(logging.DEBUG, "===================== Spear application list (%s)" % rs.pretty_print())
        
        # Store the first Spear Reference Number
        #
        if (rs.has_var("apps_dict_dict")):
            apps_dict = rs.get_var("apps_dict_dict")
            for key in apps_dict.keys():
                A2PServiceTest.SpearReferenceNumber = key
                break

    def test_get_2(self):
        """
        This function tests a request for the Spear application. 
        """
        
#        A2PServiceTest.SpearReferenceNumber = "S007789J"
        A2PServiceTest.SpearReferenceNumber = "S007533P"
#        A2PServiceTest.SpearReferenceNumber = "S1234567J"
        
        self.logger.log(logging.DEBUG, "===================== Requesting Spear application (%s)" % (A2PServiceTest.SpearReferenceNumber))
        
        if (len(A2PServiceTest.SpearReferenceNumber) > 0):
            rs = A2PServiceAPI(A2PServiceTest.spaces).get_application(A2PServiceTest.SpearReferenceNumber)
            
            # Response from A2P should look like:
            #
            #    <metadata>
            #        <item type="term:type/uri" key="term:base/datastore/resource/type">
            #            term:eplanning/spear/a2p_service/a2presponse
            #        </item>
            #    </metadata>
            #    <content>
            #        <item type="term:type/uri" key="a2p:request/uri">
            #            a2puserreq:getapplication
            #        </item>
            #        <item type="term:type/string" key="a2p:request/uuid">
            #            a72a7e83-0953-4040-a461-e5a648f0a8a7
            #        </item>
            #        <item type="term:type/string" key="spearReferenceNumber">
            #            S007533P
            #        </item>
            #        <item type="term:type/uri" key="spear_app_uri">
            #            spear:app/S007533P
            #        </item>
            #    </content>
  
            # A2P response Resource contains a URI pointing to the Spear application Resource.
            #
            
            if (rs.metadata_has_key(Uri('term:base/datastore/resource/type')) is True) and \
               (rs.get_metadata(Uri('term:base/datastore/resource/type')) == Uri('term:eplanning/spear/a2p_service/a2presponse')):
                self.logger.log(logging.DEBUG, "===================== Spear request response (%s)" % (rs.pretty_print()))
            
            if (rs.has_var("error") is True) and \
               (len(rs.get_var("error")) > 0):
                self.logger.log(logging.DEBUG, "===================== Spear request response error (%s)" % rs.get_var("error"))
            
            if (rs.has_var(Uri('a2p:request/uri')) is True) and \
               (rs.get_var(Uri('a2p:request/uri')) == Uri('a2puserreq:getapplication')):
                self.logger.log(logging.DEBUG, "===================== Spear get-application response")
                
            if (rs.has_var('a2p:request/uuid') is True):
                self.logger.log(logging.DEBUG, "===================== Spear get-application response UUID (%s)" % (rs.get_var('a2p:request/uuid')))
            
            if (rs.has_var('spearReferenceNumber') is True):
                self.logger.log(logging.DEBUG, "===================== Spear get-application response spearReferenceNumber (%s)" % (rs.get_var('spearReferenceNumber')))
            
            if (rs.has_var(Uri('spear_app_uri')) is True):
                app_rs_uri = rs.get_var(Uri('spear_app_uri'))
                app_rs = A2PServiceTest.spaces.get(app_rs_uri)
                self.logger.log(logging.DEBUG, "===================== Spear application (%s)" % app_rs.pretty_print())
        else:
            self.logger.log(logging.DEBUG, "===================== No Spear reference number")
    
    def test_get_3(self):
        """
        This function tests a request for the Spear application attachment.
        """
        
        A2PServiceTest.DocumentId = "104354"
        
        self.logger.log(logging.DEBUG, "===================== Requesting Spear application attachment (%s)" % (A2PServiceTest.DocumentId))
        
        if (len(A2PServiceTest.SpearReferenceNumber) > 0):
            rs = A2PServiceAPI(A2PServiceTest.spaces).get_application_attachment(A2PServiceTest.DocumentId)
            
            # Response from A2P should look like:
            #
            #  <metadata>
            #    <item type="term:type/uri" key="term:base/datastore/resource/type">
            #      term:eplanning/spear/a2p_service/a2presponse
            #    </item>
            #  </metadata>
            #  <content>
            #    <item type="term:type/string" key="a2p:request/uri">
            #      a2puserreq:getapplicationattachment
            #    </item>
            #    <item type="term:type/string" key="a2p:request/uuid">
            #      cd4d8164-b7f6-4ee7-938b-72b2a1e13c6f
            #    </item>
            #    <item type="term:type/string" key="documentId">
            #      104354
            #    </item>
            #    <item type="term:type/uri" key="spear_attach_uri">
            #      spear:app-attachment/104354
            #    </item>
            #  </content>
  
            # A2P response Resource contains a URI pointing to the Spear application Resource.
            #
            
            if (rs.metadata_has_key(Uri('term:base/datastore/resource/type')) is True) and \
               (rs.get_metadata(Uri('term:base/datastore/resource/type')) == Uri('term:eplanning/spear/a2p_service/a2presponse')):
                self.logger.log(logging.DEBUG, "===================== Spear request response (%s)" % (rs.pretty_print()))
            
            if (rs.has_var("error") is True) and \
               (len(rs.get_var("error")) > 0):
                self.logger.log(logging.DEBUG, "===================== Spear request response error (%s)" % rs.get_var("error"))
            
            if (rs.has_var(Uri('a2p:request/uri')) is True) and \
               (rs.get_var(Uri('a2p:request/uri')) == Uri('a2puserreq:getapplicationattachment')):
                self.logger.log(logging.DEBUG, "===================== Spear get-application-attachment response")
                
            if (rs.has_var('a2p:request/uuid') is True):
                self.logger.log(logging.DEBUG, "===================== Spear get-application-attachment response UUID (%s)" % (rs.get_var('a2p:request/uuid')))
            
            if (rs.has_var('documentId') is True):
                self.logger.log(logging.DEBUG, "===================== Spear get-application-attachment response documentId (%s)" % (rs.get_var('documentId')))
            
            if (rs.has_var(Uri('spear_attach_uri')) is True):
                app_rs_uri = rs.get_var(Uri('spear_attach_uri'))
                app_rs = A2PServiceTest.spaces.get(app_rs_uri)
                self.logger.log(logging.DEBUG, "===================== Spear application attachment (%s)" % app_rs.pretty_print())
        else:
            self.logger.log(logging.DEBUG, "===================== No Spear reference number")
        
    def test_get_4(self):
        """
        This function tests a request for the Spear User List. 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting Spear user list from Spear")
        
        rs = A2PServiceAPI(A2PServiceTest.spaces).get_user_list_from_Spear()
        
        if (rs.metadata_has_key(Uri('term:base/datastore/resource/type')) is True) and \
           (rs.get_metadata(Uri('term:base/datastore/resource/type')) == Uri('term:eplanning/spear/a2p_service/a2presponse')):
            self.logger.log(logging.DEBUG, "===================== Spear request response (%s)" % (rs.pretty_print()))
        
        if (rs.has_var("error") is True) and \
           (len(rs.get_var("error")) > 0):
            self.logger.log(logging.DEBUG, "===================== Spear request response error (%s)" % rs.get_var("error"))
        
        if (rs.has_var(Uri('a2p:request/uri')) is True) and \
           (rs.get_var(Uri('a2p:request/uri')) == Uri('a2puserreq:getuserlistfromspear')):
            self.logger.log(logging.DEBUG, "===================== Spear get-user-list-from-spear response")
        
        if (rs.has_var('a2p:request/uuid') is True):
            self.logger.log(logging.DEBUG, "===================== Spear get-user-list-from-spear response UUID (%s)" % (rs.get_var('a2p:request/uuid')))
        
        if (rs.has_var(Uri('a2p:user-list/uri')) is True):
            user_list_uri = rs.get_var(Uri('a2p:user-list/uri'))
            user_list_rs = self.spaces.get(user_list_uri)
            if (user_list_rs is not None):
                self.logger.log(logging.DEBUG, "===================== Spear user list (%s)" % user_list_rs.pretty_print())
    
    def test_get_5(self):
        """
        This function tests a request for the Spear User List. 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting cached Spear user list")
        
        rs = A2PServiceAPI(A2PServiceTest.spaces).get_user_list()
        
        if (rs.metadata_has_key(Uri('term:base/datastore/resource/type')) is True) and \
           (rs.get_metadata(Uri('term:base/datastore/resource/type')) == Uri('term:eplanning/spear/a2p_service/a2presponse')):
            self.logger.log(logging.DEBUG, "===================== Spear request response (%s)" % (rs.pretty_print()))
        
        if (rs.has_var("error") is True) and \
           (len(rs.get_var("error")) > 0):
            self.logger.log(logging.DEBUG, "===================== Spear request response error (%s)" % rs.get_var("error"))
        
        if (rs.has_var(Uri('a2p:request/uri')) is True) and \
           (rs.get_var(Uri('a2p:request/uri')) == Uri('a2puserreq:getuserlist')):
            self.logger.log(logging.DEBUG, "===================== Spear get-user-list response")
        
        if (rs.has_var('a2p:request/uuid') is True):
            self.logger.log(logging.DEBUG, "===================== Spear get-user-list response UUID (%s)" % (rs.get_var('a2p:request/uuid')))
        
        if (rs.has_var(Uri('a2p:user-list/uri')) is True):
            user_list_uri = rs.get_var(Uri('a2p:user-list/uri'))
            user_list_rs = self.spaces.get(user_list_uri)
            if (user_list_rs is not None):
                self.logger.log(logging.DEBUG, "===================== Cached Spear user list (%s)" % user_list_rs.pretty_print())
        
    def test_get_6(self):
        """
        This function tests a request for the Spear RA List. 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting Spear RA list")
        
        rs = A2PServiceAPI(A2PServiceTest.spaces).get_ra_list_from_Spear()
        
        if (rs.metadata_has_key(Uri('term:base/datastore/resource/type')) is True) and \
           (rs.get_metadata(Uri('term:base/datastore/resource/type')) == Uri('term:eplanning/spear/a2p_service/a2presponse')):
            self.logger.log(logging.DEBUG, "===================== Spear request response (%s)" % (rs.pretty_print()))
        
        if (rs.has_var("error") is True) and \
           (len(rs.get_var("error")) > 0):
            self.logger.log(logging.DEBUG, "===================== Spear request response error (%s)" % rs.get_var("error"))
        
        if (rs.has_var(Uri('a2p:request/uri')) is True) and \
           (rs.get_var(Uri('a2p:request/uri')) == Uri('a2puserreq:getralistfromspear')):
            self.logger.log(logging.DEBUG, "===================== Spear get-ra-list-from-spear response")
        
        if (rs.has_var('a2p:request/uuid') is True):
            self.logger.log(logging.DEBUG, "===================== Spear get-ra-list-from-spear response UUID (%s)" % (rs.get_var('a2p:request/uuid')))
        
        if (rs.has_var(Uri('a2p:ra-list/uri')) is True):
            ra_list_uri = rs.get_var(Uri('a2p:ra-list/uri'))
            ra_list_rs = self.spaces.get(ra_list_uri)
            if (ra_list_rs is not None):
                self.logger.log(logging.DEBUG, "===================== Spear RA list (%s)" % ra_list_rs.pretty_print())
    
    def test_get_7(self):
        """This function tests a request for the Spear RA List. 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting cached Spear RA list")
        
        rs = A2PServiceAPI(A2PServiceTest.spaces).get_ra_list()
        
        if (rs.metadata_has_key(Uri('term:base/datastore/resource/type')) is True) and \
           (rs.get_metadata(Uri('term:base/datastore/resource/type')) == Uri('term:eplanning/spear/a2p_service/a2presponse')):
            self.logger.log(logging.DEBUG, "===================== Spear request response (%s)" % (rs.pretty_print()))
        
        if (rs.has_var("error") is True) and \
           (len(rs.get_var("error")) > 0):
            self.logger.log(logging.DEBUG, "===================== Spear request response error (%s)" % rs.get_var("error"))
        
        if (rs.has_var(Uri('a2p:request/uri')) is True) and \
           (rs.get_var(Uri('a2p:request/uri')) == Uri('a2puserreq:getralist')):
            self.logger.log(logging.DEBUG, "===================== Spear get-ra-list response")
        
        if (rs.has_var('a2p:request/uuid') is True):
            self.logger.log(logging.DEBUG, "===================== Spear get-ra-list response UUID (%s)" % (rs.get_var('a2p:request/uuid')))
        
        if (rs.has_var(Uri('a2p:ra-list/uri')) is True):
            ra_list_uri = rs.get_var(Uri('a2p:ra-list/uri'))
            ra_list_rs = self.spaces.get(ra_list_uri)
            if (ra_list_rs is not None):
                self.logger.log(logging.DEBUG, "===================== Cached Spear RA list (%s)" % ra_list_rs.pretty_print())
    
    def test_get_99(self):
        """This function tests A2P polling. 
        """
        
        while (True):
            self.logger.log(logging.DEBUG, "===================== waiting for POLL")
            time.sleep(1)
    
if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    A2PServiceTest.init()
    unittest.main()